#include "notemapper.h"
#include <QDateTime>
#include <QSqlError>
#include <QSqlQuery>
#include <QSqlRecord>

Note NoteMapper::queryRecentNote()
{
    QSqlQuery query;

    QDateTime now = QDateTime::currentDateTime();
    QString ns = now.toString("yyyy-MM-dd hh:mm:ss");

    auto n = Note();
    n.exists = false;

    bool ok = query.exec(
        "select id,content,createTime,past,alarmClock from note where past != 1 and alarmClock >='"
        + ns + "'  order by alarmClock asc limit 1");

    //    qDebug() << query.lastError();

    if (ok) {
        if (query.isSelect() && query.next()) {
            n.id = query.value("id").toLongLong();
            n.past = query.value("past").toBool();
            n.content = query.value("content").toString();
            n.createTime = query.value("createTime").toString();

            n.alarmClock = query.value("alarmClock").toString();

            n.exists = true;
        }
    }

    return n;
}

void NoteMapper::saveNote(Note &n)
{
    if (n.exists) {
        QSqlQuery query;
        query.prepare(
            "update note set content = ?, createTime = ?, past = ?, alarmClock = ? where id="
            + QString::number(n.id));

        query.addBindValue(n.content);
        query.addBindValue(n.createTime);
        query.addBindValue(n.past);
        query.addBindValue(n.alarmClock);

        if (!query.exec()) {
            qDebug() << "Error:" << query.lastError();
        }

    } else {
        QSqlQuery query;
        query.prepare("insert into note(content, createTime, past, alarmClock) values(?,?,?,?)");

        query.addBindValue(n.content);
        query.addBindValue(n.createTime);
        query.addBindValue(n.past);
        query.addBindValue(n.alarmClock);
        //    qDebug() << "Bound values:" << query.boundValues();
        if (!query.exec()) {
            qDebug() << "Error:" << query.lastError();
        }
    }
}

QList<Note> NoteMapper::queryAllNotes()
{
    QList<Note> ns;

    QSqlQuery q;
    QString sql = "select id,content,createTime,past,alarmClock from note order by alarmClock desc";
    if (q.exec(sql)) {
        if (q.isSelect()) {
            while (q.next()) {
                QSqlRecord s = q.record();

                Note n;
                n.id = q.value("id").toLongLong();
                n.past = q.value("past").toBool();
                n.content = q.value("content").toString();
                n.createTime = q.value("createTime").toString();

                n.alarmClock = q.value("alarmClock").toString();

                n.exists = true;

                ns << n;
            }
        }
    }

    return ns;
}
